package com.ziroom.crm.mq.core.config;

import com.ziroom.crm.mq.core.logging.Log;
import com.ziroom.crm.mq.core.logging.LogFactory;
import com.ziroom.crm.mq.core.util.ConfigUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArraySet;


/**
 * 加载公共配置
 *
 * @author WeiShaoying
 * @since 1.0.0
 */
public final class MqConfigLoader {

    private static final Log log = LogFactory.getLog(MqConfigLoader.class);

    public static final String MQ_CONFIG_ENV_KEY = "CRM_MQ_CONFIG_FILE";

    public static final String MQ_CONFIG_PROPERTY_KEY = "crm.mq.config.file";

    private static final String DEFAULT_MQ_CONFIG_FILE = "classpath:crm-mq.properties";

    private static final Properties properties = new Properties();

    static {
        try {
            load();
        } catch (Throwable t) {
            log.warn("[SentinelConfigLoader] Failed to initialize configuration items", t);
        }
    }

    private static void load() {
        // Order: system property -> system env -> default file (classpath:sentinel.properties) -> legacy path
        String fileName = System.getProperty(MQ_CONFIG_PROPERTY_KEY);
        if (StringUtils.isBlank(fileName)) {
            fileName = System.getenv(MQ_CONFIG_ENV_KEY);
            if (StringUtils.isBlank(fileName)) {
                fileName = DEFAULT_MQ_CONFIG_FILE;
            }
        }

        Properties p = ConfigUtils.loadProperties(fileName);
        if (p != null && !p.isEmpty()) {
            log.info("[MqConfigLoader] Loading mq config from " + fileName);
            properties.putAll(p);
        }

        for (Map.Entry<Object, Object> entry : new CopyOnWriteArraySet<>(System.getProperties().entrySet())) {
            String configKey = entry.getKey().toString();
            String newConfigValue = entry.getValue().toString();
            String oldConfigValue = properties.getProperty(configKey);
            properties.put(configKey, newConfigValue);
            if (oldConfigValue != null) {
                log.info("[MqConfigLoader] JVM parameter overrides {}: {} -> {}", configKey, oldConfigValue, newConfigValue);
            }
        }
    }


    public static Properties getProperties() {
        return properties;
    }

}
